package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.YdMeterData;
import com.ruoyi.system.service.IYdMeterDataService;

/**
 * 易达电表数据Controller
 * 
 * @author ruoyi
 * @date 2024-01-15
 */
@Controller
@RequestMapping("/system/ydmeterdata")
public class YdMeterDataController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(YdMeterDataController.class);
    
    private String prefix = "system/ydmeterdata";

    @Autowired
    private IYdMeterDataService ydMeterDataService;

    @RequiresPermissions("system:ydmeterdata:view")
    @GetMapping()
    public String ydmeterdata()
    {
        return prefix + "/ydmeterdata";
    }

    /**
     * 查询易达电表数据列表
     */
    @RequiresPermissions("system:ydmeterdata:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(YdMeterData ydMeterData,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate)
    {
        startPage();
        // 如果提供了日期参数，设置日期范围条件
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            try {
                Date beginTime;
                Date endTime;
                
                // 检查startDate是否已包含时间部分
                if (startDate.length() > 10 && startDate.contains(" ")) {
                    // 已包含时间部分，直接解析
                    beginTime = DateUtils.parseDate(startDate, "yyyy-MM-dd HH:mm:ss");
                } else {
                    // 不包含时间部分，添加00:00:00
                    beginTime = DateUtils.parseDate(startDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
                }
                
                // 检查endDate是否已包含时间部分
                if (endDate.length() > 10 && endDate.contains(" ")) {
                    // 已包含时间部分，直接解析
                    endTime = DateUtils.parseDate(endDate, "yyyy-MM-dd HH:mm:ss");
                } else {
                    // 不包含时间部分，添加23:59:59
                    endTime = DateUtils.parseDate(endDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
                }
                
                // 设置查询参数
                Map<String, Object> params = new HashMap<>();
                params.put("beginTime", beginTime);
                params.put("endTime", endTime);
                ydMeterData.setParams(params);
            } catch (Exception e) {
                logger.error("日期解析错误: " + e.getMessage());
            }
        }
        List<YdMeterData> list = ydMeterDataService.selectYdMeterDataList(ydMeterData);
        return getDataTable(list);
    }

    /**
     * 导出易达电表数据列表
     */
    @RequiresPermissions("system:ydmeterdata:export")
    @Log(title = "易达电表数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(YdMeterData ydMeterData)
    {
        List<YdMeterData> list = ydMeterDataService.selectYdMeterDataList(ydMeterData);
        ExcelUtil<YdMeterData> util = new ExcelUtil<YdMeterData>(YdMeterData.class);
        return util.exportExcel(list, "易达电表数据");
    }

    /**
     * 新增易达电表数据
     */
    @RequiresPermissions("system:ydmeterdata:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存易达电表数据
     */
    @RequiresPermissions("system:ydmeterdata:add")
    @Log(title = "易达电表数据", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YdMeterData ydMeterData)
    {
        return toAjax(ydMeterDataService.insertYdMeterData(ydMeterData));
    }

    /**
     * 修改易达电表数据
     */
    @RequiresPermissions("system:ydmeterdata:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        YdMeterData ydMeterData = ydMeterDataService.selectYdMeterDataById(id);
        mmap.put("ydMeterData", ydMeterData);
        return prefix + "/edit";
    }

    /**
     * 修改保存易达电表数据
     */
    @RequiresPermissions("system:ydmeterdata:edit")
    @Log(title = "易达电表数据", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(YdMeterData ydMeterData)
    {
        return toAjax(ydMeterDataService.updateYdMeterData(ydMeterData));
    }

    /**
     * 删除易达电表数据
     */
    @RequiresPermissions("system:ydmeterdata:remove")
    @Log(title = "易达电表数据", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ydMeterDataService.deleteYdMeterDataByIds(ids));
    }

    /**
     * 统计页面
     */
    @RequiresPermissions("system:ydmeterdata:statistics")
    @GetMapping("/statistics")
    public String statistics()
    {
        return prefix + "/statistics";
    }

    /**
     * 按日统计数据
     */
    @RequiresPermissions("system:ydmeterdata:statistics")
    @PostMapping("/statisticsByDay")
    @ResponseBody
    public AjaxResult statisticsByDay(@RequestParam("startDate") String startDate,
                                     @RequestParam("endDate") String endDate)
    {
        try {
            List<Map<String, Object>> result = ydMeterDataService.statisticsByDay(startDate, endDate);
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("按日统计数据异常", e);
            return AjaxResult.error("统计数据查询失败");
        }
    }

    /**
     * 按炉号统计数据
     */
    @RequiresPermissions("system:ydmeterdata:statistics")
    @PostMapping("/statisticsByFurnace")
    @ResponseBody
    public AjaxResult statisticsByFurnace(@RequestParam("startDate") String startDate,
                                         @RequestParam("endDate") String endDate)
    {
        try {
            List<Map<String, Object>> result = ydMeterDataService.statisticsByFurnace(startDate, endDate);
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("按炉号统计数据异常", e);
            return AjaxResult.error("统计数据查询失败");
        }
    }

    /**
     * 获取设备最新数据
     */
    @RequiresPermissions("system:ydmeterdata:list")
    @PostMapping("/getLatestData")
    @ResponseBody
    public AjaxResult getLatestData(@RequestParam("deviceId") String deviceId)
    {
        YdMeterData latestData = ydMeterDataService.getLastDataByDeviceId(deviceId);
        return AjaxResult.success(latestData);
    }

    /**
     * 按炉号查询数据
     */
    @RequiresPermissions("system:ydmeterdata:list")
    @PostMapping("/getDataByFurnace")
    @ResponseBody
    public TableDataInfo getDataByFurnace(@RequestParam("furnaceNo") Integer furnaceNo,
                                         @RequestParam(value = "startDate", required = false) String startDate,
                                         @RequestParam(value = "endDate", required = false) String endDate)
    {
        startPage();
        List<YdMeterData> list = ydMeterDataService.selectDataByFurnaceNo(furnaceNo, startDate, endDate);
        return getDataTable(list);
    }

    /**
     * 按时间范围查询数据
     */
    @RequiresPermissions("system:ydmeterdata:list")
    @PostMapping("/getDataByTimeRange")
    @ResponseBody
    public TableDataInfo getDataByTimeRange(@RequestParam("startDate") String startDate,
                                           @RequestParam("endDate") String endDate,
                                           @RequestParam(value = "deviceId", required = false) String deviceId)
    {
        startPage();
        List<YdMeterData> list = ydMeterDataService.selectDataByTimeRange(startDate, endDate);
        return getDataTable(list);
    }

    /**
     * 数据详情页面
     */
    @RequiresPermissions("system:ydmeterdata:view")
    @GetMapping("/detail")
    public String detail()
    {
        return prefix + "/detail";
    }

    /**
     * 导出按时间范围查询的数据
     */
    @RequiresPermissions("system:ydmeterdata:export")
    @Log(title = "易达电表数据明细", businessType = BusinessType.EXPORT)
    @PostMapping("/exportByTimeRange")
    @ResponseBody
    public AjaxResult exportByTimeRange(@RequestParam("startDate") String startDate,
                                       @RequestParam("endDate") String endDate,
                                       @RequestParam(value = "deviceId", required = false) String deviceId)
    {
        List<YdMeterData> list = ydMeterDataService.selectDataByTimeRange(startDate, endDate);
        ExcelUtil<YdMeterData> util = new ExcelUtil<YdMeterData>(YdMeterData.class);
        return util.exportExcel(list, "易达电表数据明细");
    }

    /**
     * 导出按炉号查询的数据
     */
    @RequiresPermissions("system:ydmeterdata:export")
    @Log(title = "易达电表数据明细", businessType = BusinessType.EXPORT)
    @PostMapping("/exportByFurnace")
    @ResponseBody
    public AjaxResult exportByFurnace(@RequestParam("furnaceNo") Integer furnaceNo,
                                     @RequestParam(value = "startDate", required = false) String startDate,
                                     @RequestParam(value = "endDate", required = false) String endDate)
    {
        List<YdMeterData> list = ydMeterDataService.selectDataByFurnaceNo(furnaceNo, startDate, endDate);
        ExcelUtil<YdMeterData> util = new ExcelUtil<YdMeterData>(YdMeterData.class);
        return util.exportExcel(list, "易达电表数据明细");
    }
}